package me.dracen.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import me.dracen.mapper.UserInfoMapper;
import me.dracen.model.UserInfo;
import me.dracen.model.UserInfoExample;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Created by liuzinong on 2017/5/12.
 */
@Service
@Transactional
public class UserService {
    @Autowired
    private UserInfoMapper userInfoMapper;

    public void addUser (UserInfo user) {
        userInfoMapper.insert(user);
    }

    public List<UserInfo> findAll() {
        return userInfoMapper.selectAll();
    }

    public UserInfo findById (Integer id) {
        return userInfoMapper.selectByPrimaryKey(id);
    }

    public PageInfo<UserInfo> findByPage (UserInfo user, int offset, int limit) {
        PageInfo pageInfo = PageHelper.startPage(offset, limit).doSelectPageInfo(()-> userInfoMapper.select(user) );
        return pageInfo;
    }

    public UserInfo selectByName (String username) {
        UserInfoExample example = new UserInfoExample();
        UserInfoExample.Criteria criteria = example.createCriteria();
        criteria.andUsernameEqualTo(username);
        return userInfoMapper.selectByExample(example) ==null
                ? null :userInfoMapper.selectByExample(example).get(0);
    }

    public UserInfo getAndSave (UserInfo user) {
        UserInfo a = null;
        List<UserInfo> userInfos = userInfoMapper.select(user);
        if (userInfos != null && userInfos.size() > 0) {
            a = userInfos.get(0);
        }
        else {
            userInfoMapper.insert(user);
            a = user;
        }
        return a;
    }
}
